<template>
    <div class="activity-list">
        <el-row>
            <el-col :span="6">
                <div class="left-box">
                    <el-tabs v-model="box_index_key" @tab-click="handleClick">
                        <el-tab-pane v-for="(item, index) in box_list_arr" :key="index" :label="item.label"
                            :name="item.name">
                            <div class="select-box flex_between">
                                <el-select size="mini" class="select-w" v-model="time" placeholder="请选择"
                                    @change="selectFun">
                                    <el-option v-for="item in time_data" :key="item.id" :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                                <el-select size="mini" class="select-w" v-model="shopid_yd" placeholder="请选择"
                                    @change="selectFun">
                                    <el-option v-for="item in getYunShopList" :key="item.id" :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                            <!-- 分销有礼 数据看板 分润列表 -->
                            <template v-if="box_index_key == '-1'">
                                <div class="board-box mt10">
                                    <div class="flex_between">
                                        <div class="font_size22">数据看板</div>
                                        <div class="flex_row cursor_pointer" @click="setProfitClick">
                                            <i class="el-icon-setting"></i>
                                            <span style="margin-left: 2px;">分润设置</span>
                                        </div>
                                    </div>
                                    <div class="">
                                        <p class="font_size16">累计分润金额</p>
                                        <div class="mt5" style="line-height: 36px;">
                                            <span style="font-size: 36px;">{{ boardData.fr_num }}</span>
                                            <span class="font_size18">（元）</span>
                                        </div>
                                        <div class="flex_between">
                                            <div>
                                                <p class="font_size16">订单分润总数</p>
                                                <div class="font_size22" style="line-height: 22px;">{{ boardData.od_num
                                                    || 0 }}</div>
                                            </div>
                                            <div>
                                                <p class="font_size16">注册客户总数</p>
                                                <div class="font_size22" style="line-height: 22px;">{{ boardData.reg_num
                                                    || 0 }}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <h2 class="font_size16 mt10">分销有礼明细</h2>
                                <div :style="{ height: stateHooks.leftHeight - 260 + 'px', overflow: 'hidden' }">
                                    <LeftList :height="stateHooks.leftHeight - 260" :templates="templates"
                                        :listData="listData" :selectedIndex.sync="selectedIndex" @loadFun="loadFun"
                                        ref="leftListRef" :lLoading="lLoading" :lNoMore="lNoMore"
                                        @clickItem="clickItem">
                                        <div slot-scope="{row}" slot="do_odno" class="flex_between">
                                            <span style="font-weight: bold;">{{ row.do_odno || '-' }}</span>
                                            <span class="">
                                                <span>{{ row.status_title || '-' }}</span>
                                                <span :class="['ml10', 'bold']">￥{{ row.money || '-' }}</span>
                                            </span>
                                        </div>
                                        <div slot-scope="{row}" slot="shop_name">
                                            <span>{{ row.shop_name || '-' }}</span>
                                            <span class="ml10">{{ row.grade_title || '-' }}</span>
                                        </div>
                                    </LeftList>
                                </div>
                            </template>
                            <template v-else>
                                <div :style="{ height: stateHooks.leftHeight + 'px', overflow: 'hidden' }">
                                    <LeftList :height="stateHooks.leftHeight" :templates="templatesEventLs"
                                        :listData="listData" :selectedIndex.sync="selectedIndex" @loadFun="loadFun"
                                        ref="leftListRef" :lLoading="lLoading" :lNoMore="lNoMore"
                                        @clickItem="clickEventLsItem">
                                        <div slot-scope="{row}" slot="title" class="flex_between">
                                            <span style="font-weight: bold;">{{ row.title || '-' }}</span>
                                            <span class="">
                                                <span>{{ row.status_title || '-' }}</span>
                                            </span>
                                        </div>
                                        <div slot-scope="{row}" slot="shop_name" class="flex_row">
                                            <span class="">{{ row.shop_name || '-' }}</span>
                                            <span class="ml10">{{ row.grade_title || '-' }}</span>
                                        </div>
                                        <div slot-scope="{row}" slot="atime_tit" class="flex_row">
                                            <span class="">开始时间</span>
                                            <span class="ml10">{{ row.atime_tit || '-' }}</span>
                                        </div>
                                        <div slot-scope="{row}" slot="total_give" class="flex_row total-give"
                                            v-if="totalGive">
                                            <div>
                                                <span class="">订单总量</span>
                                                <span class="ml5">{{ row.num_od || '-' }}</span>
                                            </div>
                                            <div class="ml20">
                                                <span class="">已分润订单</span>
                                                <span class="ml5">{{ row.num_give || '-' }}</span>
                                            </div>
                                            <div class="ml20">
                                                <span class="">分润金额</span>
                                                <span class="ml5">{{ row.total_give || '-' }}</span>
                                            </div>
                                        </div>
                                    </LeftList>
                                </div>
                            </template>
                        </el-tab-pane>
                    </el-tabs>
                    <div class="iconBox">
                        <text class="icon-font search-icon" @click="addActivityList">&#xe606;</text>
                    </div>
                </div>
            </el-col>
            <el-col :span="18">
                <div class="rigth-box">
                    <template v-if="box_index_key != '-1' || isEdit">
                        <addOrEdit :getYunShopList="getYunShopSeleteList" ref="addOrEditRef" @backFun="backFun"
                            @addTpBmFun="addTpBmFun" :detailID="detailID" :isDisbableInfo="isDisbableInfo">
                        </addOrEdit>
                    </template>
                    <template v-if="box_index_key == '-1' || !isEdit">
                        <detaill ref="detaillRef" :detailGiveObj="detailGiveObj">
                        </detaill>
                    </template>
                </div>
            </el-col>
        </el-row>
        <setProfit ref="setProfitRef" @backFun="backFunSetProfit"></setProfit>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, watch, computed } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import { statusColor } from "@/utils/common.js"
import { useCommonHooks } from '@/hooks/useCommonHooks.js'

import LeftList from "@/pages/distrGifts/components/leftList.vue"
import addOrEdit from "@/pages/distrGifts/components/addOrEdit.vue"
import detaill from "@/pages/distrGifts/components/detaill.vue"
import setProfit from "@/pages/distrGifts/components/setProfit.vue"

const maxPnum = 20

// 获取当前组件实例
const { proxy } = getCurrentInstance()

// 使用全局状态
const { stateHooks } = useCommonHooks()

const lLoading = ref(false)
const lNoMore = ref(false)

// 如果是编辑页面，设置某些值不能编辑
const isDisbableInfo = ref({
    type: false,
    index_key: '-1',
})

const box_index_key = ref('2')
const selectedIndex = ref(0)
const recordSelectedIndex = ref(0)
const box_list_arr = ref([
    {
        label: "数据看板",
        name: '-1',
    },
    {
        label: "进行中",
        name: '2',
    }, {
        label: "未开始",
        name: '1',
    }, {
        label: "已停止",
        name: '3',
    }
])

// 分销明细记录
const templates = ref([
    {
        type: "slot",
        key: "do_odno",
    },
    {
        type: "init",
        key: "event_title",
    },
    {
        type: "slot",
        key: "shop_name",
    },
    {
        type: "init",
        key: "ptype_title",
    },
    {
        type: "init",
        key: "atime_tit",
    }
])

// 分销规则记录
const templatesEventLs = ref([
    {
        type: "slot",
        key: "title",
    },
    {
        type: "slot",
        key: "shop_name",
    },
    {
        type: "init",
        key: "ptype_title",
    },
    {
        type: "slot",
        key: "v_rech",
    },
    {
        type: "slot",
        key: "atime_tit",
    },
    {
        type: "slot",
        key: "total_give",
    }
])

const listData = ref([])
const detailID = ref('')
const boardData = ref({
    fr_num: 0,
    od_num: 0,
    reg_num: 0,
})

const getYunShopList = ref([{
    name: "全部云店",
    id: 0,
}])
const getYunShopSeleteList = ref([])

const time_data = ref([
    {
        id: 0,
        name: "全部日期",
    },
    {
        id: "1",
        name: "今日",
    },
    {
        id: "2",
        name: "本月",
    },
    {
        id: "3",
        name: "本季",
    },
    {
        id: "4",
        name: "本年",
    },
    {
        id: "23",
        name: "近3月",
    },
    {
        id: "26",
        name: "近6月",
    }
])

const time = ref(0)
const shopid_yd = ref(0)
const type = ref('')
const pfrom = ref(0)
const leftListRef = ref(null)
const addOrEditRef = ref(null)
const detaillRef = ref(null)

const totalGive = computed(() => {
    return box_index_key.value == '2' || box_index_key.value == '3'
})

// 新增活动
const isEdit = ref(false)
const addActivityList = () => {
    isEdit.value = true
    selectedIndex.value = null
    detailID.value = ''
    isDisbableInfo.value.type = false
    if (addOrEditRef.value) {
        isDisbableInfo.value.type = false
        addOrEditRef.value.restFun()
        addOrEditRef.value.objectForm.act = 'add'
        addOrEditRef.value.objectForm.status = 1
    }
}

// 分润设置
const setProfitRef = ref(null)
const setProfitClick = () => {
    setProfitRef.value.open()
}
const backFunSetProfit = () => {
    setProfitRef.value.close()
}

// 状态切换
const handleClick = (e) => {
    selectedIndex.value = 0
    recordSelectedIndex.value = 0
    box_index_key.value = box_list_arr.value[e.index].name
    isDisbableInfo.value.index_key = box_index_key.value
    // 状态 1未开始 2进行中 3已失效
    if (box_index_key.value == '-1') {
        isEdit.value = false
    } else {
        isEdit.value = true
    }
    if (box_index_key.value == '1') {
        isDisbableInfo.value.type = false
    } else {
        isDisbableInfo.value.type = true
    }
    refreshFun()
    getEventLs(true)
}

const refreshFun = () => {
    lNoMore.value = false
    lLoading.value = false
    pfrom.value = 0
    detailID.value = ''
    listData.value = []
}

// 选择分店
const selectFun = (e) => {
    getEventLs(true)
}

const loadFun = () => {
    if (lNoMore.value) return
    pfrom.value += 20
    getEventLs(false)
}

const getEventLs = async (t = true) => {
    lLoading.value = true
    // type  是否刷新列表
    if (t == true) {
        pfrom.value = 0
        listData.value = []
    }
    let param = {
        shopid_yd: shopid_yd.value,
        type: type.value,
        pnum: maxPnum,
        pfrom: pfrom.value,
        stime: "",
        dtime: "",
        time: time.value,
        status: box_index_key.value == '-1' ? '' : box_index_key.value,
    }
    let url = config.yx_ds_event_ls
    if (box_index_key.value == '-1') {
        url = config.yx_ds_give_ls
    }
    try {
        let res = await proxy.$api({ url: url, data: param })
        lLoading.value = false
        if (res.status == 1) {
            let result = res.data
            if (box_index_key.value != '-1') {
                console.log("resultxxxxxxxxxxxxxxxx=", result)
                boardData.value = {
                    fr_num: result.fr_amount,
                    od_num: result.fr_od_num,
                    reg_num: result.fr_u_num,
                }
            }
            console.log("boardData=", boardData.value)
            if (result.ls) {
                listData.value.push(...result.ls)
                // 确保索引在有效范围内
                const validIndex = Math.min(selectedIndex.value, listData.value.length - 1)
                detailID.value = listData.value[validIndex]?.id
                if (box_index_key.value == '-1') {
                    detailGiveObj.value = listData.value[validIndex]
                }
                if (res.status == 1 && result.ls.length < maxPnum) {
                    lNoMore.value = true
                } else {
                    lNoMore.value = false
                }
            } else {
                lNoMore.value = true;
            }
        } else {
            lNoMore.value = true
        }
    } catch (error) {
        lLoading.value = false
        lNoMore.value = true
    } finally {
        lLoading.value = false
    }
}

//  获取云店列表
const getYunShopLsFun = async () => {
    let param = {}
    try {
        let res = await proxy.$api({ url: config.YUN_SHOP_LS, data: param })
        if (res.status == 1) {
            getYunShopList.value.push(...res.data)
            getYunShopSeleteList.value = res.data
        }
    } catch (error) {
    }
}

const addTpBmFun = (e) => {
    box_index_key.value = e.status.toString()
    isDisbableInfo.value.index_key = e.status.toString()
    isEdit.value = true
    if (e.type == 'add' || e.type == 'del') {
        selectedIndex.value = 0
        refreshFun()
        getEventLs(true)
    } else {
        selectedIndex.value = recordSelectedIndex.value
        detailID.value = listData.value[recordSelectedIndex.value].id
    }
}

const detailGiveObj = ref({})
const clickItem = (index) => {
    isEdit.value = false
    selectedIndex.value = index
    recordSelectedIndex.value = index
    detailGiveObj.value = listData.value[index]
}

const clickEventLsItem = (index) => {
    isEdit.value = true
    selectedIndex.value = index
    recordSelectedIndex.value = index
    detailID.value = listData.value[index].id
}

const backFun = (e) => {
    if (e == 'back') {
        if (box_index_key.value == '-1') {
            isEdit.value = false
        } else {
            isEdit.value = true
        }
        selectedIndex.value = recordSelectedIndex.value
        detailID.value = listData.value[recordSelectedIndex.value].id
    }
}

// 正确使用 watch
watch(() => selectedIndex.value, (newValue) => {
    console.log("newValue=", newValue)
    // if (newValue == null) {
    //     detailID.value = ''
    //     return
    // }
    // if (newValue) {
    //     selectedIndex.value = newValue
    // }
    // if (listData.value && listData.value.length > 0) {
    //     // 确保索引在有效范围内
    //     const validIndex = Math.min(newValue, listData.value.length - 1)
    //     const selectedItem = listData.value[validIndex]
    //     if (selectedItem && selectedItem.id) {
    //         detailID.value = selectedItem.id
    //     } else {
    //         detailID.value = ''
    //     }
    // } else {
    //     detailID.value = ''
    // }
}, {
    immediate: true
})

// 活动记录
const activityList = (row) => {
    // TODO: Implement activity list functionality
}

onMounted(() => {
    getEventLs(true)
    getYunShopLsFun()
})

</script>

<style lang="scss" scoped>
div {
    box-sizing: border-box;
}

.board-box {
    box-sizing: border-box;
    height: 190px;
    background-color: #e22a2a;
    border-radius: 10px;
    padding: 10px 20px;
    color: #fff;
}

.activity-list {

    .left-box,
    .rigth-box {
        width: 100%;
        padding: 10px 10px 0 10px;
        height: 100vh;
        position: relative;
        border-right: 1px solid #e6e6e6;

        .iconBox {
            position: absolute;
            top: 0px;
            right: 13px;
            font-size: 26px;
            cursor: pointer;

            .search-icon {
                font-size: 20px;
                color: #333;
            }
        }

        .marketing-add {
            width: 100%;
        }
    }

    .status_txt {
        position: absolute;
        right: 20px;
        top: 33px;
    }

    .list_btn {
        position: absolute;
        bottom: 10px;
        right: 20px;
        z-index: 9;
    }
}

.ellipsis2 {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.left-box {
    .select-w {
        width: 49%;
    }
}

.total-give {
    border-top: 1px solid #e6e6e6;
    padding-top: 10px;
    margin-top: 10px;
}
</style>